import Koa, { Context } from 'koa'
import KoaBody from 'koa-body'
import Cors from 'koa2-cors'
import Path from 'path'
import testController from '@/koa-server/controller/TestController'
import { getLogger } from '@/koa-server/util/Log4jsUtil'
import AddressIP from 'ip'
import Session from 'koa-session'
import { errorHandler } from '@/koa-server/middlewares/ErrorHandler'

const logger = getLogger('app')
const app = new Koa()

const CONFIG = {
  key: 'sessionId',
  maxAge: 86400000,
  autoCommit: true,
  overwrite: true,
  httpOnly: true,
  signed: true,
  rolling: false,
  renew: false,
}

app.use(Session(CONFIG, app))

// 文件上传配置
app.use(
  KoaBody({
    // 支持文件格式
    multipart: true,
    formidable: {
      // 上传目录
      uploadDir: Path.join(__dirname, '../public/uploads'),
      // 保留文件扩展名
      keepExtensions: true,
      // 设置上传文件大小最大限制，默认2M
      maxFileSize: 200 * 1024 * 1024,
    },
  })
)

// 跨域配置
app.use(
  Cors({
    origin: function (ctx: Context) {
      return '*'
    },
    exposeHeaders: ['Authorization'],
    maxAge: 5 * 24 * 60 * 60,
    credentials: true,
    allowMethods: ['GET', 'POST', 'OPTIONS', 'DELETE', 'PUT'],
    allowHeaders: [
      'Content-Type',
      'Authorization',
      'Accept',
      'X-Requested-With',
    ],
  })
)

// 统一异常处理一定要放在所有路由配置之前
app.use(errorHandler)

// 路由配置
app.use(testController.routes()).use(testController.allowedMethods())

const port = 4000
app.listen(port, () => {
  logger.info(
    `\nkoa服务启动: \n${AddressIP.address()}:${port}\n127.0.0.1:${port}`
  )
})
